package com.xuyuan.spring.bean;

import lombok.Data;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class BeanDefinitionBuilderExample {
    public static void main(String[] args) {
        // 利用spring的机制，交给spring管理对应自定义的对象
        // 创建一个BeanFactory TODO 使用spring提供的BeanFactory
        BeanDefinitionRegistry registry = new DefaultListableBeanFactory();

        // 创建BeanDefinitionBuilder TODO GenericBeanDefinition.class 是创建对应BeanDefinition的默认实现
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(MyBean.class);
        // 设置属性 // 添加Bean的属性
        beanDefinitionBuilder.addPropertyValue("name", "BeanName");
        // 获取BeanDefinition对象
        BeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
        // 注册BeanDefinition
        registry.registerBeanDefinition("myBean", beanDefinition);
        // 创建Spring容器
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(String.valueOf(registry));

        // 获取并使用Bean
        MyBean myBean = context.getBean(MyBean.class);
        myBean.printName();

        // 关闭容器
        context.close();
    }

    @Data
    static class MyBean {
        private String name;

        public void printName() {
            System.out.println(name);
        }
    }
}